﻿#include <QFile>
#include <QJsonValueRef>
#include <QDebug>
#include <QtAlgorithms>
#include <QtConcurrent/QtConcurrent>

#include "DeviceManager.h"
#include "JsonUtils.h"
#include "CommunicationManager.h"
#include "WaitUtils.h"
//#include "StatusDbItem.h"
//#include "DBManager.h"
//#include "SampleItem.h"
#include "apputils.h"

DeviceManager::DeviceManager()
{
    _factory=new BaseDeviceFactory();
}

DeviceManager::~DeviceManager()
{
}

DeviceManager& DeviceManager::Instance()
{
    static DeviceManager _instance;
    return _instance;
}

QList<BaseDevice*> DeviceManager::GetDevices(QJsonArray names)
{
    return GetItems<BaseDevice>(names);
}

void DeviceManager::WaitForMonitorPause()
{
    _needMonitor=false;
    while(_isMonitoring)
    {
        WaitUtils::WaitMs(100);
    }
}

void DeviceManager::StartMonitor()
{
    _needMonitor=true;
}

void DeviceManager::SetMonitorInterval(int intervalSecond)
{
    if(_monitorDeviceId!=0)
    {
        killTimer(_monitorDeviceId);
    }
    _monitorDeviceId=startTimer(intervalSecond*1000);
}


void DeviceManager::SetEnableDeviceMonitor(bool enableMonitor)
{
    _enableMonitor=enableMonitor;
}


void DeviceManager::RecordItem(DeviceStateItems itemList)
{
//    if(_isRecord)
//    {
//        StatusDbItem item;
//        item.TimeKey= SampleItem::Datetime2Stringzzz(itemList.TimeKey);
//        item.ExtendInformation=DeviceStateItems::ConvertToJsonObj(itemList);
//        DBManager::Instance().ResetDb();
//        DBManager::Instance().SaveItem(item);
//    }
}

void DeviceManager::timerEvent(QTimerEvent *event)
{
    if(!_enableMonitor)
    {
        return;
    }

//    if(!_needMonitor)
//    {
//        return;
//    }

    _isMonitoring=true;
    QElapsedTimer timer;
    timer.start();
    DeviceStateItems ret;
    try
    {
        for(auto item:GetItems<BaseDevice>())
        {
            QElapsedTimer t;
            t.start();
            ret.append(item->GetDeviceStateItems());
            if(t.elapsed()>200)
            {
                qDebug()<<item->Name()<<"状态更新耗时较长:"<<t.elapsed()<<"ms";
            }
        }
    }
    catch(QString err)
    {
        qDebug()<<__FUNCTION__<<__LINE__<<err;
    }
    catch(QException ex)
    {
        qDebug()<<__FUNCTION__<<__LINE__<<ex.what();
    }
    ret.TimeKey=QDateTime::currentDateTime();
    _stateItems=ret;
    emit StateUpdated(_stateItems);
    if(timer.elapsed()>500)
    {
        qDebug()<<"设备状态更新耗时较长:"<<timer.elapsed()<<"ms  "<<AppUtils::GetCurrentRAMAsMB()<<"mb";
    }
    _isMonitoring=false;
}

void DeviceManager::SetRecord(bool isRecord)
{
    _isRecord=isRecord;
}

void DeviceManager::Stop()
{
    for(auto device:GetItems<BaseDevice>())
    {
        device->Stop();
    }

    qDebug()<<__FUNCTION__<<__LINE__<<"device stop!";
}

void DeviceManager::Reset()
{
    for(auto device:GetItems<BaseDevice>())
    {
        device->Reset();
    }
}

void DeviceManager::WaitForEnd()
{
    killTimer(_monitorDeviceId);
    Stop();
}
